package org.easymodelers.gmf.utils;

import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;

public abstract class MetaModelUtils {

	public static EClass getMetaModelEClass(EPackage metaModel, String name) {
		System.out.println("name = "+name);
		for (TreeIterator<EObject> i = metaModel.eAllContents(); i.hasNext();) {
			EObject o = i.next();
			if (o instanceof EClass) {
				EClass c = (EClass)o;
				System.out.println("c = "+c.getName());
				if (c.getName().equals(name)) {
					System.out.println(" -> found");
					return (EClass)o;
				}
			}
		}
		return null;
	}

	public static EAttribute getMetaModelEAttribute(EPackage metaModel, String className, String attributeName) {
		System.out.println("name = "+className+"."+attributeName);
		for (TreeIterator<EObject> i = metaModel.eAllContents(); i.hasNext();) {
			EObject o = i.next();
			if (o instanceof EClass) {
				EClass clazz = (EClass)o;
				System.out.println("c = "+clazz.getName());
				if (clazz.getName().equals(className)) {
					for (EAttribute attribute : clazz.getEAllAttributes()) {
						System.out.println("- a = "+attribute.getName());
						if (attribute.getName().equals(attributeName)) {
							System.out.println(" -> found");
							return attribute;
						}
					}
				}
			}
		}
		return null;
	}

	public static EReference getMetaModelEReference(EPackage metaModel, String className, String referenceName) {
		System.out.println("name = "+className+"."+referenceName);
		for (TreeIterator<EObject> i = metaModel.eAllContents(); i.hasNext();) {
			EObject o = i.next();
			if (o instanceof EClass) {
				EClass clazz = (EClass)o;
				System.out.println("c = "+clazz.getName());
				if (clazz.getName().equals(className)) {
					for (EReference reference : clazz.getEAllReferences()) {
						System.out.println("- r = "+reference.getName());
						if (reference.getName().equals(referenceName)) {
							System.out.println(" -> found");
							return reference;
						}
					}
				}
			}
		}
		return null;
	}
}
